// app.js
import { globalStore } from "./store/index";
import { appConfig } from "./config/appConfig";
import { applyTabBar } from "./utils/tabBar";

const originalPage = Page;
Page = function (options) {
  const onLoad = options?.onLoad;
  const onShow = options?.onShow;
  return originalPage({
    ...options,
    onLoad(this: WechatMiniprogram.Component.TrivialInstance, ...args: any[]) {
      if (this.route) {
        console.log(`load page: ${this.route}.wxml`);
      }
      if (typeof onLoad === "function") {
        onLoad.apply(this, args);
      }
    },
    onShow(this: WechatMiniprogram.Component.TrivialInstance, ...args: any[]) {
      if (this.route) {
        console.log(`show page: ${this.route}.wxml`);
      }
      if (typeof onShow === "function") {
        onShow.apply(this, args);
      }
    },
  });
};

App({
  onLaunch() {
    if (appConfig.useCloud) {
      if (!wx.cloud) {
        console.error("请使用 2.20.0 或以上的基础库以使用云能力");
      } else {
        wx.cloud.init({
          env: globalStore.envId,
          traceUser: true,
        });
      }
    }

    globalStore.initAppData().then(() => {
      applyTabBar(globalStore.isChef ? "chef" : globalStore.isDiner ? "diner" : "guest");
    });
  },

  onPageNotFound(res) {
    console.warn("页面未找到", res);
  },

  onShow(options) {
    console.log("App onShow", options);
    applyTabBar(globalStore.isChef ? "chef" : globalStore.isDiner ? "diner" : "guest");
  },

  globalStore,
});
